package com.itheima.im.socket.core;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import com.itheima.im.socket.bean.QQMessage;

public class QQConnnection extends Thread {
	private String ip;
	private int port;

	// Alt+Shift+S

	public QQConnnection(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}
	// 搞来搞去就这4步
	// 1.打开通道
	// 2.关闭通道
	// 3.发送消息
	// 4.接收消息
	// 5 需要修改的地方就是读写消息的方式
	private Socket client = null;
	private DataInputStream reader;
	private DataOutputStream writer;

	private boolean isRunning = true;

	// 打开连接
	public void connect() throws Exception {
		client = new Socket(ip, port);
		reader = new DataInputStream(client.getInputStream());
		writer = new DataOutputStream(client.getOutputStream());
	
		this.start();
	}
	
	@Override
	public void run() {
		super.run();
		while (isRunning) {
		try {
			/**
			 * 发送消息
			 * @see #sendMessage(QQMessage)
			 * */
			String xml = reader.readUTF();//阻塞的方式接收消息
			QQMessage msg = new QQMessage();
			msg = (QQMessage) msg.fromXml(xml);
			if (msg != null) {
				// 登录代码处理
				// 解析好友列表
				// 下线成功
				for (OnReceiveMsgListener listener : listeners) {
					listener.onReceive(msg);
				}
			}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 添加多个监听
	private List<OnReceiveMsgListener> listeners = new ArrayList<OnReceiveMsgListener>();

	public void addOnReceiveMsgListener(OnReceiveMsgListener listener) {
		listeners.add(listener);
	}

	public void removeOnReceiveMsgListener(OnReceiveMsgListener listener) {
		listeners.remove(listener);
	}

	// 断开
	public void disconnect() {
		isRunning = false;
		this.interrupt();// 中断该线程
		if (writer != null) {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (client != null) {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 发送消息
	public void sendMessage(QQMessage msg) throws Exception {
		String xml = msg.toXml();
		if (writer != null) {
			writer.writeUTF(xml);
		}
	}
}
